package stack_queue.queue.iml;

import stack_queue.queue.Queue;

import java.util.NoSuchElementException;

/**
 * @Author: wenjingyuan
 * @Date: 2022/09/28/17:31
 * @Description:基于链表的队列
 * 队首出，队尾进
 */
public class LinkedQueue implements Queue {
    private Node head;
    private Node tail;
    private int size;
    private class Node{
        private int data;
        private Node next;

        public Node(int data) {
            this.data = data;
        }
    }
    /**
     * 入队操作
     * @param val
     */
    @Override
    public void offer(int val) {
        //新元素
        Node node=new Node(val);
        if(head==null){
            head=tail=node;
        }else{
            tail.next=node;
            tail=node;
        }
     size++;
    }

    @Override
    public int poll() {
     if(size==0){
         throw new NoSuchElementException("队列为空！");
     }
     int oldValue= head.data;
     Node temp=head;
     head=head.next;
     temp.next=null;
     size--;
     return oldValue;
    }

    @Override
    public int peek() {
        if(size==0){
            throw new NoSuchElementException("队列为空！");
        }
        return head.data;
    }

    @Override
    public String toString() {
       StringBuilder sb=new StringBuilder();
       sb.append('[');
       Node node=head;
       while(node!=null){
       sb.append(node.data);
       if(node.next!=null){
           sb.append(',');
       }
       node=node.next;
       }
       sb.append(']');
       return sb.toString();
    }
}
